<template>
	<view v-if="pageShow">
		<u--form :model="formData" ref="uForm" :rules="rules" :labelPosition="formJson.labelPosition"
			:labelWidth="formJson.labelWidth">
			<template v-for="(fies,findex) in formJson.fields">
				<template v-if="fies.__config__.layout=='colFormItem'">
					<u-form-item :ref="fies.__config__.formId"
						:label="fies.__config__.showLabel?fies.__config__.label:''" :key="findex"
						:labelWidth="fies.__config__.labelWidth" :required="fies.__config__.required"
						:prop="fies.__vModel__">
						<template v-if="fies.__config__.tag=='el-input'">
							<!-- 文本输入框 -->
							<u--input v-if="fies.__config__.tagIcon=='input'" v-model="formData[fies.__vModel__]"
								:placeholder="fies.placeholder" :clearable="fies.clearable"
								:disabled="fies.disabled||openType==2||openType==4">
								<u--text v-if="fies.__slot__.prepend" :text="fies.__slot__.prepend" slot="prefix"
									margin="0 3px 0 0" type="tips"></u--text>
								<u--text v-if="fies.__slot__.append" :text="fies.__slot__.append" slot="suffix"
									margin="0 3px 0 0" type="tips"></u--text>
							</u--input>
							<!-- 密码输入框 -->
							<u--input v-if="fies.__config__.tagIcon=='password'" password
								v-model="formData[fies.__vModel__]" :placeholder="fies.placeholder"
								:clearable="fies.clearable"
								:disabled="fies.disabled||openType==2||openType==4"></u--input>
							<u--textarea v-if=" fies.__config__.tagIcon=='textarea'" :placeholder=" fies.placeholder"
								v-model="formData[fies.__vModel__]"
								:disabled="fies.disabled||openType==2||openType==4"></u--textarea>
						</template>
						<template v-else-if="fies.__config__.tag=='el-input-number'">
							<!-- 计数器 -->
							<u--number-box v-if="fies.__config__.tagIcon=='number'" v-model="formData[fies.__vModel__]"
								:placeholder="fies.placeholder"
								:disabled="fies.disabled||openType==2||openType==4"></u--number-box>
						</template>
						<template v-else-if="fies.__config__.tag=='el-select'">
							<view class="inputView u--border u--input u-border u-input"
								@click="openPicker(fies.__slot__.options,fies.__vModel__,fies.disabled||openType==2||openType==4)">
								<text v-if="!formData[fies.__vModel__]" class="placeholder">{{fies.placeholder}}</text>
								<text v-else>{{formData[fies.__vModel__+'Label']}}</text>
							</view>

						</template>
						<template v-else-if="fies.__config__.tag=='el-cascader'">
							<uni-data-picker :localdata="setCascaderData(fies.options)"
								v-model="formData[fies.__vModel__]" :popup-title="'请选择'+fies.__config__.label"
								:placeholder="fies.placeholder"
								:readonly="fies.disabled||openType==2||openType==4"></uni-data-picker>
						</template>
						<template v-else-if="fies.__config__.tag=='el-radio-group'">
							<u-radio-group v-if="fies.__config__.tagIcon=='radio'" iconPlacement="left" placement="row"
								v-model="formData[fies.__vModel__]" :disabled="fies.disabled||openType==2||openType==4">
								<u-radio :disabled="fies.disabled||openType==2||openType==4"
									:customStyle="{marginBottom: '8px',marginRight:'8px'}"
									v-for="(item, index) in fies.__slot__.options" :key="index" :label="item.label"
									:name="item.value">
								</u-radio>
							</u-radio-group>
						</template>
						<template v-else-if="fies.__config__.tag=='el-radio-checkbox'">
							<u-checkbox-group v-if="fies.__config__.tagIcon=='checkbox'" placement="row"
								v-model="formData[fies.__vModel__]" :disabled="fies.disabled||openType==2||openType==4">
								<u-checkbox :disabled="fies.disabled||openType==2||openType==4"
									:customStyle="{marginBottom: '8px',marginRight:'8px'}"
									v-for="(item, index) in fies.__slot__.options" :key="index" :label="item.label"
									:name="item.value">
								</u-checkbox>
							</u-checkbox-group>
						</template>
						<!-- 日期选择器 -->
						<template v-else-if="fies.__config__.tag=='el-date-picker'">
							<!-- <view class="inputDisBox">
								<u--input v-model="formData[fies.__vModel__]" :placeholder="fies.placeholder"
									:clearable="fies.clearable" disabled disabledColor="#ffffff">
									<uni-icons type="right" size="40rpx" slot="suffix" color="#ddd"></uni-icons>
								</u--input>
								<view class="inputDis" @click="openDatetime(fies.__vModel__)"></view>
							</view> -->
							<view class="inputView u--border u--input u-border u-input"
								@click="openDatetime(fies.__vModel__)">
								<text v-if="!formData[fies.__vModel__]" class="placeholder">{{fies.placeholder}}</text>
								<text v-else>{{dateFormat(formData[fies.__vModel__])}}</text>
							</view>
						</template>
					</u-form-item>
				</template>
			</template>
			<u-form-item label="照片" required prop="picture" v-if="uploadImg">
				<u-upload width="160rpx" height="160rpx" :fileList="fileList" @afterRead="afterRead($event, 'fileList')"
					@delete="deletePic($event, 'fileList')" multiple accept="image">
				</u-upload>
			</u-form-item>
			<u-form-item label="是否通过" required prop="isPass" v-if="isPass||openType==2">
				<u-radio-group v-model="formData.isPass" iconPlacement="left" v-if="openType==4&&isPass">
					<u-radio label="通过" :disabled="openType==2" name="1" style="margin-right: 20rpx;"></u-radio>
					<u-radio label="驳回" :disabled="openType==2" name="2"></u-radio>
				</u-radio-group>
				<template v-else>
					<view class="statusBtn" :class="statusClass[formData.isPass]">
						{{formData.isPass==1?'通过':'驳回'}}
					</view>
				</template>
			</u-form-item>
			<slot name="def"></slot>
			<view class="btn" @click="submit" v-if="openType!=2">{{btnText}}</view>
		</u--form>
		<u-picker :show="pickerShow" :columns="columns" keyName="label" @confirm="pickerConfirm" @close="pickerClose"
			@cancel="pickerCancel"></u-picker>
		<u-datetime-picker :minDate="-4607395543000" ref="datetimePicker" :show="datetimeShow" v-model="datetimeValue"
			mode="date" @confirm="datetimeConfirm" @close="closePicker('datetimeShow')"
			@cancel="closePicker('datetimeShow')"></u-datetime-picker>
	</view>
</template>

<script>
	import * as uploadApi from "@/api/upload.js"
	import * as util from "@/utils/util.js";
	export default {
		name: "dynamicForms",
		props: {
			uploadImg: {
				type: Boolean,
				default: false
			},
			btnText: {
				type: String,
				default: '立即报名',
			},
			openType: {
				type: [String, Number],
				default: '3',
			},
			isPass: {
				type: Boolean,
				default: false
			},
		},
		data() {
			return {
				IMGMaxSize: 1024 * 1024 * 5,
				fileList: [],
				fileList_imgs: [],
				fileList_old: [],
				openName: '',
				datetimeValue: Number(new Date()),
				pageShow: false,
				pickerDataName: '',
				pickerShow: false,
				datetimeShow: false,
				formData: {
					isPass: '',
				},
				columns: [],
				// defaultValue
				formJson: {
					fields: []
				},
				rules: {

				},
				statusClass: ['def', 'pass', 'fail'],
			};
		},

		methods: {
			initFormData(componentList, formData) {
				componentList.forEach(cur => {
					const config = cur.__config__
					if (cur.__vModel__) formData[cur.__vModel__] = config.defaultValue
					if (config.children) this.initFormData(config.children, formData)
				})
			},
			deletePic(event, dataStr) {
				this[dataStr].splice(event.index, 1)
				if (typeof(this[dataStr + '_imgs']) === 'string') {
					this[dataStr + '_imgs'] = ''
				} else {
					this[dataStr + '_imgs'].splice(event.index, 1)
				}
				console.log(this[dataStr + '_imgs'])
			},
			beforeRead(file, lists) {
				// const {
				// 	name,
				// 	size,
				// 	type
				// } = file
				const imgTypes = ['bmp', 'jpg', 'png', 'jpeg']
				const IMGMaxSize = this.IMGMaxSize
				file.forEach(item => {
					const isJPG = imgTypes.indexOf(item.type) !== -1;
					const sizeT = item.size <= IMGMaxSize
				})
				console.log(file, lists);
				return sizeT && isJPG
			},
			// 新增图片
			async afterRead(event, dataStr) {
				console.log(event, dataStr)
				const that = this
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[dataStr].length
				//备份 失败回调
				that[dataStr + '_old'] = JSON.parse(JSON.stringify(that[dataStr]))
				lists.map(item => {
					that[dataStr].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await that
						.uploadFilePromise(lists[i].url, dataStr)
						.then(res => {
							return res
						})
						.catch(() => {
							// that[dataStr] = that[dataStr + '_old']
							return false
						})
					if (result) {
						let item = that[dataStr][fileListLen]
						that[dataStr].splice(
							fileListLen,
							1,
							Object.assign(item, {
								status: 'success',
								message: '',
								url: result.url
							})
						)
						fileListLen++
					} else {
						let item = that[dataStr][fileListLen]
						that[dataStr].splice(
							fileListLen,
							1
						)
					}
					that[dataStr + '_old'] = JSON.parse(JSON.stringify(that[dataStr]))
				}
			},
			uploadFilePromise(url, dataStr) {
				return new Promise((resolve, reject) => {
					uploadApi
						.upload(url)
						.then((
							data
						) => {
							console.log(data)
							const {
								fileName,
								newFileName,
								originalFilename,
								url
							} = data
							const imgData = {
								fileName,
								newFileName,
								originalFilename,
								url
							}
							if (Object.prototype.toString.call(this[dataStr + '_imgs']) ===
								'[object Array]') {
								this[dataStr + '_imgs'].push(imgData)
							} else if (Object.prototype.toString.call(this[dataStr + '_imgs']) ===
								'[object String]') {
								this[dataStr + '_imgs'] = imgData
							}
							resolve(imgData)
						})
						.catch(reject)
				})
			},
			closePicker(showName) {
				this[showName] = false
				this.openName = ''
			},
			dateFormat(time, format = "YYYY-mm-dd") {
				return util.dateFormat(time, format)
			},
			openDatetime(name) {
				this.datetimeShow = true
				this.openName = name
			},
			datetimeConfirm({
				mode,
				value
			}) {
				const openName = this.openName
				// this.$set(this.formData, openName, value)
				this.formData[openName] = value
				this.datetimeShow = false
				console.log(this.formData[openName]);
			},
			formatter(type, value) {
				if (type === 'year') {
					return `${value}年`
				}
				if (type === 'month') {
					return `${value}月`
				}
				if (type === 'day') {
					return `${value}日`
				}
				return value
			},
			submit() {
				const that = this
				// that.$refs.uForm.setRules(this.rules)
				if (this.uploadImg && this.fileList.length > 0) {
					that.formData.picture = JSON.stringify(this.fileList)
				} else {
					that.formData.picture = null
				}
				const formData = that.formData
				const formJson = that.formJson
				that.$refs.uForm.validate().then(res => {
					if (this.openType == 3) {
						for (let key in formData) {
							formJson.fields.forEach(item => {
								if (item.__vModel__ == key) {
									item.__config__.defaultValue = formData[key]
								}
							})
							// console.log(key, formData[key]);
						}
						if (this.uploadImg && this.fileList.length > 0) {
							that.$emit('submit', that.formJson, that.formData.picture)
						} else {
							that.$emit('submit', that.formJson)
						}
					} else {
						this.$emit('submit', formData)
					}
				}).catch(errors => {
					console.log(errors);
				})

			},
			initData(data, formData = null) {
				const that = this
				// let rules = {}
				// let rules1 = {
				// 	type: 'any',
				// 	required: true,
				// 	message: '不能为空',
				// 	trigger: ['change', 'blur'],
				// }
				// data.fields.forEach(item => {
				// 	if (item.__config__.regList.length > 0) {
				// 		rules[item.__vModel__] = item.__config__.regList.concat([rules1])
				// 	} else {
				// 		rules[item.__vModel__] = rules1
				// 	}
				// })
				let rules = {}
				let rules1 = [{
					type: 'any',
					required: true,
					message: '不能为空',
					trigger: ['change', 'blur'],
				}]
				data.fields.forEach(item => {
					rules[item.__vModel__] = item.__config__.regList.concat([rules1])
				})
				if (this.uploadImg) {
					rules.picture = [{
						type: 'any',
						min: 1,
						required: true,
						message: '请上传图片',
						trigger: ['change', 'blur'],
					}]
				}
				if (this.isPass) {
					rules.isPass = [{
						type: 'string',
						min: 1,
						required: true,
						message: '请选择是否通过',
						trigger: ['change', 'blur'],
					}]
				}

				this.rules = rules
				this.formJson = data
				this.pageShow = true
				// this.$nextTick(() => {
				// 	console.log(that.$refs.uForm, that.$refs);
				// 	that.$refs.uForm.setRules(rules)
				// })
				this.initFormData(this.formJson.fields, this.formData)
				if (formData && this.openType == 2) {
					this.formData.isPass = formData.isPass
				}
			},
			openPicker(data, name, flag = false) {
				if (!flag) {
					this.columns = [data]
					this.pickerShow = true
					this.pickerDataName = name
				}
			},
			setCascaderData(datas) {
				datas.forEach(item => {
					item.text = item.label
					if (item.children) {
						this.setCascaderData(item.children)
					}
				})
				console.log(datas);
				return datas
			},
			pickerConfirm({
				value
			}) {
				const pickerDataName = this.pickerDataName
				console.log(value[0], pickerDataName);
				this.pickerShow = false
				this.formData[pickerDataName + 'Label'] = value[0].label
				this.formData[pickerDataName] = value[0].value
			},
			pickerClose() {
				this.pickerShow = false
				this.pickerDataName = ''
			},
			pickerCancel() {
				this.pickerShow = false
				this.pickerDataName = ''
			}
		},
		watch: {
			// pageShow(newV) {
			// 	if (newV) {
			// 		this.$nextTick(() => {
			// 			console.log(this.$refs.uForm, this.$refs);
			// 			this.$refs.uForm.setRules(this.rules)
			// 		})
			// 	}
			// }
		}
	}
</script>

<style lang="scss" scoped>
	@import "@/components/dynamicForms/dynamicForms.scss";
</style>